package com.gelapps.memogel.login;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import com.gelapps.memogel.AboutActivity;
import com.gelapps.memogel.Constants;
import com.gelapps.memogel.Functions;
import com.gelapps.memogel.R;
import com.gelapps.memogel.MainActivity;
import com.gelapps.memogel.password.FunctionsPass;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

    private final static int MENU_ABOUT=1;
	//private EditText txtMasterPassword;
	private String eKey;

	/**
	 * Metodo chiamato alla creazione dell'attivita
	 */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    /**
     * Metodo chiamato dopo che l'attivita e stata messa in sottofondo e prima di rimandarla up
     */
    protected void onResume()
    {
    	super.onResume();
    	//if (getBaseContext().getFileStreamPath(Constants.getDirFileConf()).exists()) {
    		//Log.i("OnResume", "Esiste la directory");
    	if (getBaseContext().getFileStreamPath(Constants.getPathMasterPWD()).exists())
    		{//Se esiste la master password
    			Log.i("OnResume", "Esiste la master Password ");
    			setContentView(R.layout.login);
    			//txtMasterPassword = (EditText) findViewById(R.id.txtMasterPass);
    			Button btnCheckPass = (Button) findViewById(R.id.btnOKMP);
    			btnCheckPass.setOnClickListener(checkMasterPasswordListener);
    		}//}
    	else
    	{//Non esiste la master password
    		Log.i("onResume", "Non esiste o non si ha accesso al file di master pass");
    		Log.i("onResume", "Esiste: " + String.valueOf(getBaseContext().getFileStreamPath(Constants.getPathMasterPWD()).exists()));
    		setContentView(R.layout.create_master_p);
    		Button btnCreatePass = (Button) findViewById(R.id.linearLayout1);
         	btnCreatePass.setOnClickListener(createPassListener);
    	}
    }
    
    /**
     * Metodo chiamato quando un'altra attivit� viene messa in primo piano e questa passa in secondo
     */
    protected void onPause()
    {
    	super.onPause();
    	//this.okLogin = false;						//Necessario?
    }
    
    /**
     * Listener del button per la creazione della master password
     */
    private OnClickListener createPassListener = new OnClickListener()
    {
		@Override
		public void onClick(View v) {
			EditText eTxtPwd1 = (EditText) findViewById(R.id.etxtPwd1);
			EditText eTxtPwd2 = (EditText) findViewById(R.id.etxtPWD2);
			if (Functions.partialAnd(eTxtPwd1.getText().toString().length()==eTxtPwd2.getText().toString().length(), eTxtPwd1.getText().toString().equals(eTxtPwd2.getText().toString())))
				if (!(createMasterPassFile(eTxtPwd1.getText().toString())))
				{//Errore nella creazione della master password
					TextView txtError = (TextView) findViewById(R.id.txtErrorCreatePWD);
					txtError.setText(R.string.strMasterPasswordCreate);
					
					//TODO Utilizzare i toast
				}
				else
				{//Master password creata
					eKey = FunctionsPass.getInstance().getHashSHA256(eTxtPwd1.getText().toString());
					//Setto le preferenze di default
					SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
					SharedPreferences.Editor editor = preferences.edit();
					editor.putBoolean(Constants.getPrefCard(), true);
					editor.putBoolean(Constants.getPrefCredential(), true);
					editor.putBoolean(Constants.getPrefAccount(), false);
					editor.commit();

					launchSubActivity();
				}
			else
			{ //Errore nella creazione della master password (le due password non coincidono)
				TextView txtError = (TextView) findViewById(R.id.txtErrorCreatePWD);
				txtError.setText(R.string.strErrorCreateMasterPass);
				
				//TODO Utilizzare i toast
				
			}		
		}
    };
    
    /**
     * Listener del button per il check della master password
     */
    private OnClickListener checkMasterPasswordListener = new OnClickListener()
    {

		@Override
		public void onClick(View arg0) {
			EditText txtMasterPassword = (EditText) findViewById(R.id.txtMasterPass);
			String passInserita = FunctionsPass.getInstance().getHashSHA256(txtMasterPassword.getText().toString());
			Log.i("checkMasterPasswordListener", "pass inserita: "+passInserita);
			String passSalvata = loadMasterPass();
			Log.i("checkMasterPasswordListener", "pass salvata: "+passSalvata);
			if (FunctionsPass.getInstance().checkPass(passInserita, passSalvata))
			{
				eKey = passSalvata;
				launchSubActivity();
			}
			else
			{
				TextView txtError = (TextView) findViewById(R.id.txtErrorCreatePWD);
				txtError.setText(R.string.strErrorCheckMasterPassword);
				
				//TODO Utilizzare i Toast
			}

		}
    	
    };
    
    /**
     * Metodo per lanciare l'attività dell'app dopo aver fatto il check della pass
     */
    private void launchSubActivity()
    {
		Bundle bundle = new Bundle();
		bundle.putString(Constants.getKeyString(),this.eKey);
    	Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    	intent.putExtras(bundle);
    	startActivity(intent);
    }
    
    /**
     * Metodo per la creazione del file con la master password
     * @param pass
     * @return
     */
    private boolean createMasterPassFile(String pass)
    {
    	Writer writer = null;
    	try
    	{
    		writer = new OutputStreamWriter(openFileOutput(Constants.getPathMasterPWD(), MODE_PRIVATE));
    		writer.write(FunctionsPass.getInstance().getHashSHA256(pass));
    		writer.flush();
    	}
    	catch (IOException e)
    	{
    		Log.e("MainActivity", "Errore nella creazione dell file della master Pass");
    	}
    	finally {
    		if (writer!=null)
    			try{writer.close();}catch(Throwable t){}
    	}
    	return true;
    }
    
    /**
     * Metodo per la lettura della master password
     * @return il checksum della master password
     */
    private String loadMasterPass()
    {
    	String ret=null;
    	Reader reader = null;
    	try{
    		reader = new InputStreamReader(openFileInput(Constants.getPathMasterPWD()));
    		StringBuffer aux = new StringBuffer();
    		char[] buf = new char[1024];		//2  Lunghezza SHA controllare
    		int len;
    		while ((len = reader.read(buf))!= -1){aux.append(buf,0,len);}
    		ret = aux.toString();
    	}
    	catch(FileNotFoundException e)
    	{
    		ret =null;
    	}
    	catch (IOException e)
    	{
    		Log.e("MainActivity", "Impossibile aprire il file");
    	}
    	finally {if (reader!=null){try {reader.close();}catch(Throwable t){}}
    	}
    	return ret;
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu)				//TODO Terminare
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		menu.add(menu.NONE,MENU_ABOUT,0,R.string.strMenuAbout);
		return true;
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
		//super.onOptionsItemSelected(item);
		switch(item.getItemId())
		{
		case MENU_ABOUT:{Log.i("OnOptionsItemSelected","menu about");
                        Intent i = new Intent(LoginActivity.this, AboutActivity.class);
                        startActivity(i);
                        return true;}
		}
		return false;
	}

	public boolean onPrepareOptionsMenu(Menu menu)
	{
		return super.onPrepareOptionsMenu(menu);
	}
}
